//
//  ZYDataModificationVC.m
//  YiLin
//
//  Created by Zyark on 2018/5/31.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYDataModificationVC.h"
#import "ZYModifyUsernameVC.h"
#import "ZYModifyPasswordVC.h"
#import "ZYModifyPhoneEmailVC.h"
#import "ZYModifyProblemVC.h"
#import "ZYGesturePasswordVC.h"
#import "ImageUploadTools.h"
#import "ZYUser.h"
#import "JDStatusBarNotification.h"

#define HEAD_VIEW_HEIGHT 100

@interface ZYDataModificationVC ()<UITableViewDelegate,UITableViewDataSource,ImageUploadToolsDelegate>
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) UIView *headView;
@property(nonatomic,strong) UIImageView *headImageView;
@property(nonatomic,copy) NSString *nickname;
@property(nonatomic,copy) NSString *headUrl;
@property(nonatomic,copy) NSString *phone;
@property(nonatomic,copy) NSString *email;
@property(nonatomic,strong) NSArray *titleArray;
@property(nonatomic,strong) ImageUploadTools *imageUploadTools;
@end

@implementation ZYDataModificationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupUserInfo];
    self.title = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_ME_MAIN_DATA_MODIFICATION];
}

#pragma mark -init
-(void)setup{
    [self setupHeadView];
    [self setupTableView];
    [self setupImageUploadTools];
}

-(void)setupImageUploadTools{
    _imageUploadTools = [ImageUploadTools new];
    NSString *token = [ZYConfig loginToken];
    _imageUploadTools.url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_UPLOAD_HEAD_URL];
    _imageUploadTools.params = @{@"ssid":token};
    _imageUploadTools.filename = @"header";
    _imageUploadTools.delegate = self;
}

-(void)setupTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H - self.navigationView.height)];
    [self.view addSubview:_tableView];
    _tableView.top = self.navigationView.bottom;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.scrollEnabled = NO;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
//    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

-(void)setupHeadView{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, HEAD_VIEW_HEIGHT)];
    headView.backgroundColor = [UIColor whiteColor];
    [headView setUserInteractionEnabled:YES];
    
    CGFloat headImageWidth = ZYSCREEN_W * 0.2;
    UIImageView *headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, headImageWidth, headImageWidth)];
    [headView addSubview:headImageView];
    headImageView.centerX = headView.centerX;
    headImageView.top = 0;
    headImageView.layer.cornerRadius = headImageView.frame.size.width / 2;
    headImageView.layer.masksToBounds = YES;
    headImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uploadImage)];
    [headImageView addGestureRecognizer:tap];
    
    UILabel *nicknameLabel = [[UILabel alloc] init];
    nicknameLabel.width = headView.width;
    nicknameLabel.height = 20;
    [headView addSubview:nicknameLabel];
    nicknameLabel.centerX = headView.centerX;
    nicknameLabel.top = headImageView.bottom + 8;
    nicknameLabel.textColor = RGBA(204, 204, 204, 1);
    nicknameLabel.font = [UIFont systemFontOfSize:12];
    nicknameLabel.textAlignment = NSTextAlignmentCenter;
    nicknameLabel.text = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_ME_MAIN_HEAD_EDIT];
    _headView = headView;
    _headImageView = headImageView;
}

-(void)setupUserInfo{
    ZYUser *user = [ZYConfig userInfo];
    _nickname = user.username;
    _phone = user.phone;
    _headUrl = user.headImageUrl;
    if(!NULLString(_headUrl)){
        [_headImageView setImageURL:[NSURL URLWithString:_headUrl]];
    }else{
        [_headImageView setImage:[UIImage imageNamed:@"ic_default_head"]];
    }
    [self.tableView reloadData];
}


/**
 tableview cell detailLabel文字位置自定义
 @param cell cell
 @return label
 */
-(UILabel *)setupDetailLabelWithCell:(UITableViewCell *)cell{
    UILabel *detailLabel = [[UILabel alloc] init];
    detailLabel.size = cell.detailTextLabel.size;
    [cell addSubview:detailLabel];
    detailLabel.textAlignment = NSTextAlignmentLeft;
    detailLabel.textColor = cell.detailTextLabel.textColor;
    detailLabel.font = cell.detailTextLabel.font;
    [detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell).offset(cell.width / 3);
        make.centerY.equalTo(cell.mas_centerY);
        make.right.equalTo(cell).offset(-30);
    }];
    return detailLabel;
}

#pragma mark - TableViewDelegate datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0){
        return 1;
    }
    return 6;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        return HEAD_VIEW_HEIGHT;
    }
    return 45;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    if (section == 2) {
        view.size = CGSizeMake(ZYSCREEN_W, 20);
        UIView *line = [[UIView alloc] init];
        line.size = CGSizeMake(ZYSCREEN_W - 30, 1);
        line.backgroundColor = RGBA(248, 248, 248, 1);
        [view addSubview:line];
        line.centerY = view.height / 2;
        line.left = 15;
    }
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * ID = @"cell";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
//    if(cell == nil){
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
//    }
    //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    cell.backgroundColor = [UIColor whiteColor];
    switch (indexPath.section) {
        case 0:
            [cell addSubview:self.headView];
            [cell setUserInteractionEnabled:YES];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;
            break;
        case 1:
            //用户名 手机号 邮箱 登录密码 手势密码 问题设置
            cell.textLabel.text = self.titleArray[indexPath.row];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//            cell.detailTextLabel.textAlignment = NSTextAlignmentLeft;
            if(indexPath.row < 2){
                UILabel *detailLabel = [self setupDetailLabelWithCell:cell];
                if(indexPath.row == 0){
                    detailLabel.text = _nickname;
                }else if(indexPath.row == 1){
                    detailLabel.text = _phone;
                }
            }
            break;
        default:
            break;
    }
//    if(indexPath.section == 1){
//        if(indexPath.row < 2){
//            [cell.detailTextLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.equalTo(cell).offset(cell.width / 3);
//                make.centerY.equalTo(cell.mas_centerY);
//            }];
//        }
//    }
    return cell;
}

#pragma mark - TableView delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if(indexPath.section == 1){
        if(indexPath.row == 0){//用户名
            ZYModifyUsernameVC *vc = [[ZYModifyUsernameVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if(indexPath.row == 1){//手机号
            ZYModifyPhoneEmailVC *vc = [[ZYModifyPhoneEmailVC alloc] init];
            vc.type = ZYModifyTypePhone;
            [self.navigationController pushViewController:vc animated:YES];
        }else if(indexPath.row == 2){//邮箱
            ZYModifyPhoneEmailVC *vc = [[ZYModifyPhoneEmailVC alloc] init];
            vc.type = ZYModifyTypeEmail;
            [self.navigationController pushViewController:vc animated:YES];
        }else if(indexPath.row == 3){//修改密码
            ZYModifyPasswordVC *vc = [[ZYModifyPasswordVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if(indexPath.row == 4){//手势密码
            ZYGesturePasswordVC *vc = [[ZYGesturePasswordVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if(indexPath.row == 5){//问题设置
            ZYModifyProblemVC *vc = [[ZYModifyProblemVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

#pragma mark - ImageUploadToolsDelegate
-(void)begin{
    [JDStatusBarNotification showWithStatus:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_UPLOAD_IMAGE_IN]];
}

-(void)success:(id)responseObject{
    [JDStatusBarNotification dismiss];
    NSString *code = [responseObject objectForKey:@"code"];
    if([code integerValue] == 200){
        ZYUser *user = [ZYUser modelWithJSON:[responseObject objectForKey:@"result"]];
        [ZYConfig saveUserInfo:user];
        [_headImageView setImageURL:[NSURL URLWithString:user.headImageUrl]];
        [self.tableView reloadData];
        [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_UPLOAD_IMAGE_SUCCESS]];
    }else{
        //        [JDStatusBarNotification showWithStatus:responseObject[@"message"] dismissAfter:1.0f];
        NSString *errorMessage = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:[NSString stringWithFormat:@"code_%@",code]];
        [[ToastHelper sharedToastHelper] toastError:errorMessage];
    }
    
}

-(void)progress:(NSProgress *)uploadProgress{
    [JDStatusBarNotification showProgress:uploadProgress.fractionCompleted];
}

-(void)failure:(NSError *)error{
    [JDStatusBarNotification dismiss];
    [[ToastHelper sharedToastHelper] toastError:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_UPLOAD_IMAGE_FAIL]];
    //    [JDStatusBarNotification showWithStatus:@"上传图片失败,请重新选择图片." dismissAfter:1.0f];
}

#pragma mark - Event
-(void)uploadImage{
    [_imageUploadTools alertSelectImage:self];
}

#pragma mark - Getter
-(NSArray *)titleArray{
    if(!_titleArray){
        ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
        //用户名 手机号 邮箱 登录密码 手势密码 问题设置
        _titleArray = @[[language getStringByKey:LC_ME_MAIN_DATA_EDIT_USERNAME],[language getStringByKey:LC_ME_MAIN_DATA_EDIT_PHONE],[language getStringByKey:LC_ME_MAIN_DATA_EDIT_EMAIL],[language getStringByKey:LC_ME_MAIN_DATA_EDIT_PASSWORD],[language getStringByKey:LC_ME_MAIN_DATA_EDIT_GESTURE_PASSWORD],[language getStringByKey:LC_ME_MAIN_DATA_EDIT_PROBLEM_SETTINGS]];
    }
    return _titleArray;
}

@end
